package user_api

import (
	"ginBolg/global"
	"ginBolg/models"
	"ginBolg/models/res"
	"ginBolg/plugins/email"
	"ginBolg/utils"
	"ginBolg/utils/jwt"
	"ginBolg/utils/random"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

type BindEmailRequest struct {
	Email    string  `json:"email" binding:"required,email" msg:"邮箱格式不正确"`
	Code     *string `json:"code"`
	Password string  `json:"password" binding:"required" msg:"请输入密码"`
}

func (UserApi) UserBindEmailView(c *gin.Context) {
	_claims, _ := c.Get("claims")
	claims := _claims.(*jwt.CustomClaims)
	var cr BindEmailRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailWithError(err, &cr, c)
		return
	}
	session := sessions.Default(c)
	if cr.Code == nil {
		code := random.Code(4)
		// 写入session
		session.Set("valid_code", code)
		err := session.Save()
		if err != nil {
			global.Log.Error(err)
			res.Fail("session错误", c)
			return
		}
		err = email.NewCode().Send(cr.Email, "您的验证码是："+code)
		if err != nil {
			global.Log.Error(err)
		}
		res.OkWithMessage("验证码已发送，请查收", c)
		return
	}
	// 校验验证码
	code := session.Get("valid_code")
	if code != *cr.Code {
		res.Fail("验证码错误", c)
		return
	}
	// 修改用户的邮箱
	var user models.UserModel
	err = global.DB.Take(&user, claims.UserId).Error
	if err != nil {
		res.Fail("用户不存在", c)
		return
	}
	if len(cr.Password) < 4 {
		res.Fail("密码强度太低", c)
		return
	}
	hashPwd := utils.HashAndSalt(cr.Password)
	err = global.DB.Model(&user).Updates(map[string]any{
		"email":    cr.Email,
		"password": hashPwd,
	}).Error
	if err != nil {
		global.Log.Error(err)
		res.Fail("邮箱绑定失败", c)
		return
	}
	res.OkWithMessage("邮箱绑定成功", c)
	return
}
